<script lang="ts" setup>
import type { DataType } from '../../types';

import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';
import { $t } from '#/locales';
import { useVbenModal } from '@vben/common-ui';
import { cloneDeep } from '@vben/utils';

import {
  Button,
  Dropdown,
  Image,
  Menu,
  MenuItem,
  message,
  Modal,
  Popconfirm,
  Space,
  Switch,
} from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteNavMenu,
  getNavMenuInfo,
  getNavMenus,
  postNavMenusListOrder,
  putNavMenu,
} from '#/api/admin/navMenus';
import { getNavsSelectNavs } from '#/api/admin/navs';
import Icon from '#/components/Icons';
import { handleTree, sortByField, toggleStatus } from '#/utils';

import DataFormModalView from './DataFormModal.vue';

//转义&
function decodeHtml(html: string) {
  const txt = document.createElement('textarea');
  txt.innerHTML = html;
  return txt.value;
}


const navID = ref();
const navMenus: any = ref([]);
const menus = ref([{ id: 0, name: $t("admin.As a primary navigation item") }]);
const [TableModal, modalApi] = useVbenModal();
const gridOptions: VxeGridProps<DataType> = {
  rowConfig: {
    useKey: true,
    drag: true,
  },
  columnConfig: {
    useKey: true,
  },
  columns: [
    { field: 'id', title: $t("page.common.Code"), width: 50, dragSort: true },
    { 
      field: 'name', 
      title: $t("page.common.Name"), 
      treeNode: true , 
      slots: {
        default: ({ row }) => {
          // 使用 v-html 渲染原始内容（避免转义）
          return h('div', {  innerHTML: decodeHtml(row.name) });
        }
      }
    },
    // { field: 'target', title: '打开方式' },
   {
      field: 'is_social',
      title: $t("page.common.Category"),
      slots: {
        default: ({ row }) => {
          return h(
            'Tag',
            {
              color: row.is_social === 1 ? 'blue' : 'green' // 可选：添加不同颜色
            },
            row.is_social === 1 ? '社交媒体' : '导航'
          );
        }
      }
    },
    {
      slots: { default: 'action' },
      field: 'action',
      fixed: 'right',
      title: '操作',
      width: 240,
    },
  ],
  treeConfig: {
    parentField: 'parent_id',
    rowField: 'id',
    transform: true,
  },
  exportConfig: {},
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async () => {
        const modalData = modalApi.getData();
        navID.value = modalData.id;
        const { data } = await getNavMenus({ nav_id: modalData.id });
        navMenus.value = data.list;
        data.list = sortByField(data.list, 'list_order');
        return data;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
});

const gridEvents: VxeGridListeners<DataType> = {
  async rowDragend() {
    const visibleData = GridApi.grid.getTableData().visibleData;
    const result: { [key: string]: number } = {};
    // 使用 forEach 替代 reduce
    visibleData.forEach((item, index) => {
      result[item.id] = index;
    });
    await postNavMenusListOrder({ list_orders: result });
  },
};

const handleDelete = async (row: DataType) => {
  const $table = GridApi.grid;
  if ($table) {
    const { msg } = await deleteNavMenu(row.id);
    $table.remove(row);
    message.success(msg);
  }
};

const [DataFormModal, formModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: DataFormModalView,
  onClosed() {
    const formModalData = formModalApi.getData();
    if (formModalData?.isUpdata) {
      GridApi.query();
    }
  },
});
function formatHigherDeptOptions(treeList: any) {
  // 根据返回数据的status字段值判断追加是否禁用disabled字段，返回处理后的树结构，用于上级菜单级联选择器的展示（实际开发中也是如此，不可能前端需要的每个字段后端都会返回，这时需要前端自行根据后端返回的某些字段做逻辑处理）
  if (!treeList || treeList.length === 0) return;
  const newTreeList = [];
  for (const element of treeList) {
    if (typeof element.rule !== 'string') {
      element.disabled = true;
      element.rule = `${element.rule.action}?${JSON.stringify(element.rule.param)}`;
    }
    delete element.html;
    formatHigherDeptOptions(element.children);
    newTreeList.push(element);
  }
  return newTreeList;
}
const openDialog = async (
  title: 'Add' | 'Add Sub Navigation' | 'Edit',
  row?: any | DataType,
  type: 'add' | 'edit' = 'add',
) => {
  menus.value = [
    { id: 0, name: $t("admin.As a primary navigation item"), children: [] },
    ...handleTree(navMenus.value, 'id', 'parent_id'),
  ];
  const {
    data: { navs },
  } = await getNavsSelectNavs();
  const newRow = cloneDeep(row) || {
    parent_id: 0,
    status: 1,
    nav_id: navID.value,
  };
  if (row?.id) {
    const is_hewf =['home','news','aboutus','sxs','atv','contact','parts','accessories','smart','resource/dealer','resource/distributor','promotions','salesnetwork/global','salesnetwork/distributor'];
    if (
      (newRow.href && newRow.href.charAt(0) === '{') || is_hewf.includes(newRow.href)
    ) {
      
      const {
        data: { item },
      } = await getNavMenuInfo(row.id);
      newRow.href = item.href;
      newRow.external_href = '';
      newRow.nav_id = row.nav_id;
    } else {
      newRow.external_href = row.href;
      newRow.href = '';
      newRow.nav_id = row.nav_id;
    }
  }
  if (type === 'add') {
    newRow.parent_id = 0;
    newRow.status = 1;
    newRow.nav_id = navID.value;
  }
  if (type === 'add' && row?.id) {
    newRow.parent_id = row.id;
    newRow.id = null;
    newRow.status = 1;
    newRow.href = '';
    newRow.name = '';
    newRow.list_order = 10_000;
    newRow.nav_id = row.nav_id;
  }
  formModalApi.setState({
    title: `${title}数据`,
  });

  formModalApi.setData({
    form: newRow,
    menus: menus.value,
    navs: formatHigherDeptOptions(cloneDeep(navs)),
  });
  formModalApi.open();
};

const onChange = async (row: DataType) => {
  Modal.confirm({
    title: '系统提示',
    content: `确认要${row.status === 0 ? '隐藏' : '显示'}吗?`,
    async onOk() {
      try {
        await putNavMenu(row.id);
        message.success(`已${row.status === 0 ? '隐藏' : '显示'}`);
      } catch {
        row.status = toggleStatus(row.status);
      }
    },
    onCancel() {
      row.status = toggleStatus(row.status);
    },
  });
};
</script>
<template>
  <TableModal :footer="false" class="w-3/5">
    <DataFormModal />

    <Grid :grid-events="gridEvents" :table-title="$t('page.common.List')">
      <template #toolbar-tools>
        <Button class="mr-2" type="primary" @click="openDialog('Add')">
          <span class="anticon">
            <Icon icon="ri:add-line" />
          </span>
          {{$t("admin.Add Data")}} 
        </Button>
      </template>
      <template #image="{ row }">
        <Image v-if="row.image" :src="row.image" height="20" width="20" />
      </template>
      <template #status="{ row }">
        <Switch
          v-model:checked="row.status"
          :checked-value="1"
          :un-checked-value="0"
          checked-children="显示"
          un-checked-children="隐藏"
          @change="onChange(row)"
        />
      </template>
      <template #action="{ row }">
        <Space>
          <Button type="primary" @click="openDialog('Edit', row, 'edit')">
            <template #icon>
              <span class="anticon">
                <Icon icon="ri:file-edit-line" />
              </span>
            </template>
            {{$t("page.common.Edit")}}
          </Button>
          <Popconfirm
            :cancel-text="$t('page.common.No')"
            :ok-text="$t('page.common.Yes')"
            :title="$t('page.common.Confirm Delete')"
            @confirm="handleDelete(row)"
          >
            <Button danger type="primary">
              <template #icon>
                <span class="anticon">
                  <Icon icon="ri:delete-bin-line" />
                </span>
              </template>
              {{$t("page.common.Delete")}}
            </Button>
          </Popconfirm>
          <Dropdown>
            <Button type="link">
              <template #icon>
                <span class="anticon">
                  <Icon icon="ri:more-fill" />
                </span>
              </template>
            </Button>
            <template #overlay>
              <Menu>
                <MenuItem>
                  <Button
                    type="link"
                    @click="openDialog('Add Sub Navigation', row, 'add')"
                  >
                    <template #icon>
                      <span class="anticon">
                        <Icon icon="ri:add-line" />
                      </span>
                    </template>
                    {{$t('admin.Add Sub Navigation')}}
                  </Button>
                </MenuItem>
              </Menu>
            </template>
          </Dropdown>
        </Space>
      </template>
    </Grid>
  </TableModal>
</template>
